<template>
  <div class="requirements-container">
    <div class="top-bar">
      <div class="top-left">
        <img src="../assets/logo.png" alt="系统Logo" class="logo" />
        <span class="title">皮革产品打样需求管理系统</span>
      </div>

      <div class="detail-title">
        <span>{{ isEdit ? '编辑项目' : '新建项目' }}</span>
      </div>

      <div class="buttons">
        <button class="primary-button" @click="goBack">
          <i class="iconfont icon-back"></i> 返回列表
        </button>
      </div>
    </div>

    <div class="main-content" v-loading="isLoading">
      <el-form :model="form" label-position="top" class="requirement-form">
        <!-- 项目基本信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <h2>项目基本信息</h2>
            </div>
          </template>

          <div class="form-row">
            <el-form-item label="项目名称" required>
              <el-input v-model="form.project_name" placeholder="请输入项目名称"></el-input>
            </el-form-item>
            <el-form-item label="项目编号" required>
              <el-input v-model="form.project_code" placeholder="请输入项目编号"></el-input>
            </el-form-item>
            <el-form-item label="客户名称">
              <el-input v-model="form.client_name" placeholder="请输入客户名称"></el-input>
            </el-form-item>
          </div>

          <div class="form-row">
            <el-form-item label="客户联系人">
              <el-input v-model="form.client_contact" placeholder="请输入客户联系人"></el-input>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="form.client_phone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </div>

          <div class="form-row">
            <el-form-item label="项目目标" class="full-width">
              <el-input v-model="form.project_goal" type="textarea" :rows="3" placeholder="请输入项目目标"></el-input>
            </el-form-item>
          </div>
        </el-card>

        <!-- 需求详情 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <h2>需求详情</h2>
              <el-button type="primary" @click="addRequirement">添加需求</el-button>
            </div>
          </template>

          <el-tabs
              v-model="outerActiveTab"
              type="card"
              class="outer-tabs"
              @tab-change="innerActiveTab = 'design'"
          >
            <el-tab-pane v-for="(requirement, index) in form.requirements" :key="index" :label="'需求 ' + (index + 1)">
              <div class="requirement-header">
                <el-button v-if="form.requirements.length > 1" type="danger" size="small" @click="removeRequirement(index)">
                  删除
                </el-button>
              </div>
              <el-tabs v-model="innerActiveTab">
                <!-- 产品设计细节 -->
                <el-tab-pane label="产品设计细节" name="design">
                  <div class="form-content">
                    <div class="form-row">
                      <el-form-item label="文件名称">
                        <el-input v-model="requirement.file_name" placeholder="请输入文件名称"></el-input>
                      </el-form-item>
                      <el-form-item label="版本">
                        <el-input v-model="requirement.version" placeholder="请输入版本号"></el-input>
                      </el-form-item>
                    </div>

                    <div class="form-row">
                      <el-form-item label="产品形状">
                        <el-select
                            v-model="requirement.product_shape"
                            placeholder="请选择产品形状"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="正方形" value="正方形"></el-option>
                          <el-option label="长方形" value="长方形"></el-option>
                          <el-option label="流线型" value="流线型"></el-option>
                          <el-option label="圆形" value="圆形"></el-option>
                          <el-option label="不规则" value="不规则"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="产品结构">
                        <el-select
                            v-model="requirement.product_structure"
                            placeholder="请选择产品结构"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="单层" value="单层"></el-option>
                          <el-option label="多层" value="多层"></el-option>
                          <el-option label="带口袋" value="带口袋"></el-option>
                          <el-option label="可折叠" value="可折叠"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>

                    <div class="form-row">
                      <el-form-item label="闭合类型">
                        <el-select
                            v-model="requirement.closure_type"
                            placeholder="请选择闭合类型"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="拉链" value="拉链"></el-option>
                          <el-option label="纽扣" value="纽扣"></el-option>
                          <el-option label="磁吸" value="磁吸"></el-option>
                          <el-option label="挂钩" value="挂钩"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="装饰">
                        <el-input v-model="requirement.decoration" placeholder="请输入装饰信息"></el-input>
                      </el-form-item>
                    </div>

                    <div class="form-row">
                      <el-form-item label="口袋类型">
                        <el-select
                            v-model="requirement.pocket_type"
                            placeholder="请选择口袋类型"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="拉链袋" value="拉链袋"></el-option>
                          <el-option label="贴袋" value="贴袋"></el-option>
                          <el-option label="隐形袋" value="隐形袋"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="尺寸">
                        <el-input v-model="requirement.dimensions" placeholder="请输入尺寸"></el-input>
                      </el-form-item>
                    </div>

                    <div class="form-row">
                      <el-form-item label="颜色代码">
                        <div class="color-preview-wrapper">
                          <el-input v-model="requirement.color_code" placeholder="请输入颜色代码"></el-input>
                          <div class="color-preview" :style="{ backgroundColor: isValidColor(requirement.color_code) ? requirement.color_code : 'transparent' }"></div>
                        </div>
                      </el-form-item>
                      <el-form-item label="颜色色调">
                        <el-select
                            v-model="requirement.color_shade"
                            placeholder="请选择颜色色调"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="深色" value="深色"></el-option>
                          <el-option label="浅色" value="浅色"></el-option>
                          <el-option label="中性色" value="中性色"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>

                    <div class="form-row">
                      <el-form-item label="图案类型">
                        <el-select
                            v-model="requirement.pattern_type"
                            placeholder="请选择图案类型"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="压花" value="压花"></el-option>
                          <el-option label="印花" value="印花"></el-option>
                          <el-option label="雕刻" value="雕刻"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="图案位置">
                        <el-input v-model="requirement.pattern_location" placeholder="请输入图案位置"></el-input>
                      </el-form-item>
                    </div>

                    <div class="form-row">
                      <el-form-item label="图案尺寸">
                        <el-input v-model="requirement.pattern_size" placeholder="请输入图案尺寸"></el-input>
                      </el-form-item>
                      <el-form-item label="优先级">
                        <el-select
                            v-model="requirement.priority"
                            placeholder="请选择优先级"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="高" value="高"></el-option>
                          <el-option label="中" value="中"></el-option>
                          <el-option label="低" value="低"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>
                </el-tab-pane>

                <!-- 材质偏好 -->
                <el-tab-pane label="材质偏好" name="material">
                  <div class="form-content">
                    <div class="form-row">
                      <el-form-item label="皮革类型">
                        <el-select
                            v-model="requirement.leather_type"
                            placeholder="请选择皮革类型"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="全粒面" value="全粒面"></el-option>
                          <el-option label="反绒" value="反绒"></el-option>
                          <el-option label="人造革" value="人造革"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="皮革厚度">
                        <el-input v-model="requirement.leather_thickness" placeholder="请输入皮革厚度"></el-input>
                      </el-form-item>
                    </div>

                    <div class="form-row">
                      <el-form-item label="皮革表面处理">
                        <el-select
                            v-model="requirement.leather_finish"
                            placeholder="请选择皮革表面处理"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="哑光" value="哑光"></el-option>
                          <el-option label="亮光" value="亮光"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="内衬类型">
                        <el-select
                            v-model="requirement.lining_type"
                            placeholder="请选择内衬类型"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="涤纶" value="涤纶"></el-option>
                          <el-option label="超纤" value="超纤"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>

                    <div class="form-row">
                      <el-form-item label="内衬颜色">
                        <el-input v-model="requirement.lining_color" placeholder="请输入内衬颜色"></el-input>
                      </el-form-item>
                    </div>
                  </div>
                </el-tab-pane>

                <!-- 预期效果 -->
                <el-tab-pane label="预期效果" name="effect">
                  <div class="form-content">
                    <div class="form-row">
                      <el-form-item label="柔软度">
                        <el-select
                            v-model="requirement.softness"
                            placeholder="请选择柔软度"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="非常柔软" value="非常柔软"></el-option>
                          <el-option label="适中" value="适中"></el-option>
                          <el-option label="偏硬" value="偏硬"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="耐用性">
                        <el-select
                            v-model="requirement.durability"
                            placeholder="请选择耐用性"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="高" value="高"></el-option>
                          <el-option label="中" value="中"></el-option>
                          <el-option label="低" value="低"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>

                    <div class="form-row">
                      <el-form-item label="防水性">
                        <el-select
                            v-model="requirement.water_resistance"
                            placeholder="请选择防水性"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="完全防水" value="完全防水"></el-option>
                          <el-option label="防泼水" value="防泼水"></el-option>
                          <el-option label="不防水" value="不防水"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="光泽度">
                        <el-select
                            v-model="requirement.shine"
                            placeholder="请选择光泽度"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="哑光" value="哑光"></el-option>
                          <el-option label="半哑" value="半哑"></el-option>
                          <el-option label="自然" value="自然"></el-option>
                          <el-option label="高光" value="高光"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>
                </el-tab-pane>

                <!-- 工艺要求 -->
                <el-tab-pane label="工艺要求" name="process">
                  <div class="form-content">
                    <div class="form-row">
                      <el-form-item label="切割精度">
                        <el-select
                            v-model="requirement.cutting_accuracy"
                            placeholder="请选择切割精度"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="±1mm" value="±1mm"></el-option>
                          <el-option label="±2mm" value="±2mm"></el-option>
                          <el-option label="±3mm" value="±3mm"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="缝纫密度">
                        <el-select
                            v-model="requirement.sewing_density"
                            placeholder="请选择缝纫密度"
                            filterable
                            allow-create
                            default-first-option
                        >
                          <el-option label="8-9针/英寸" value="8-9针/英寸"></el-option>
                          <el-option label="10-12针/英寸" value="10-12针/英寸"></el-option>
                          <el-option label="12-14针/英寸" value="12-14针/英寸"></el-option>
                        </el-select>
                      </el-form-item>
                    </div>

                    <div class="form-row">
                      <el-form-item label="组装顺序" class="full-width">
                        <el-input v-model="requirement.assembly_order" type="textarea" :rows="3" placeholder="请输入组装顺序"></el-input>
                      </el-form-item>
                    </div>
                  </div>
                </el-tab-pane>

                <!-- 成本要求 -->
                <el-tab-pane label="成本要求" name="cost">
                  <div class="form-content">
                    <div class="form-row">
                      <el-form-item label="材料成本">
                        <el-input v-model="requirement.material_cost" placeholder="请输入材料成本"></el-input>
                      </el-form-item>
                      <el-form-item label="加工成本">
                        <el-input v-model="requirement.processing_cost" placeholder="请输入加工成本"></el-input>
                      </el-form-item>
                    </div>
                  </div>
                </el-tab-pane>

                <!-- 生产可行性 -->
                <el-tab-pane label="生产可行性" name="feasibility">
                  <div class="form-content">
                    <div class="form-row">
                      <el-form-item label="工艺可行性">
                        <el-input v-model="requirement.process_feasibility" placeholder="请输入工艺可行性评估"></el-input>
                      </el-form-item>
                      <el-form-item label="生产周期">
                        <el-input v-model="requirement.production_time" placeholder="请输入预计生产周期"></el-input>
                      </el-form-item>
                    </div>

                    <div class="form-row">
                      <el-form-item label="需求描述" class="full-width">
                        <el-input v-model="requirement.requirement_desc" type="textarea" :rows="3" placeholder="请输入需求描述"></el-input>
                      </el-form-item>
                    </div>

                    <div class="form-row">
                      <el-form-item label="备注" class="full-width">
                        <el-input v-model="requirement.notes" type="textarea" :rows="3" placeholder="请输入备注信息"></el-input>
                      </el-form-item>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </el-tab-pane>
          </el-tabs>
          <div class="form-actions">
            <el-button type="primary" @click="onSubmit" :loading="isSubmitting">{{ isEdit ? '保存修改' : '创建项目' }}</el-button>
            <el-button @click="goBack">取消</el-button>
          </div>
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { ElNotification } from 'element-plus';

const route = useRoute();
const router = useRouter();
const activeTab = ref('design');
const isLoading = ref(false);
const isSubmitting = ref(false);
const projectOptions = ref([]);
const outerActiveTab = ref(0); // 外层Tab控制需求切换
const innerActiveTab = ref('design'); // 内层Tab控制分类切换

// 判断是新建还是编辑
const isEdit = computed(() => {
  return route.params.id && route.params.id !== 'new';
});

// 创建空需求的方法
const createEmptyRequirement = () => ({
  file_name: '',
  version: '',
  priority: '中',
  product_shape: '',
  product_structure: '',
  closure_type: '',
  decoration: '',
  pocket_type: '',
  dimensions: '',
  color_code: '',
  color_shade: '',
  pattern_type: '',
  pattern_location: '',
  pattern_size: '',
  leather_type: '',
  leather_thickness: '',
  leather_finish: '',
  lining_type: '',
  lining_color: '',
  softness: '',
  durability: '',
  water_resistance: '',
  shine: '',
  cutting_accuracy: '',
  sewing_density: '',
  assembly_order: '',
  material_cost: '',
  processing_cost: '',
  process_feasibility: '',
  production_time: '',
  requirement_desc: '',
  notes: ''
});

// 表单数据
const form = reactive({
  // 项目基本信息
  project_name: '',
  project_code: '',
  client_name: '',
  client_contact: '',
  client_phone: '',
  project_goal: '',

  // 需求数组
  requirements: [createEmptyRequirement()]
});

// 添加需求
const addRequirement = () => {
  form.requirements.push(createEmptyRequirement());
  outerActiveTab.value = form.requirements.length - 1;
  innerActiveTab.value = 'design'; // 重置内层Tab
};

// 删除需求
const removeRequirement = (index) => {
  form.requirements.splice(index, 1);
  if (form.requirements.length === 0) {
    form.requirements.push(createEmptyRequirement());
  }
  activeTab.value = 'design-0';
};

// 获取项目选项列表
const fetchProjectOptions = async () => {
  try {
    const token = localStorage.getItem('token');
    const response = await axios.get('/api/projects', {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    projectOptions.value = response.data.data || [];
  } catch (error) {
    console.error('获取项目选项失败:', error);
  }
};

// 获取项目详情
const fetchProjectDetails = async () => {
  if (!isEdit.value) return;

  try {
    isLoading.value = true;
    const token = localStorage.getItem('token');
    const projectId = route.params.id;

    // 获取项目基本信息
    const projectResponse = await axios.get(`/api/projects/${projectId}`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    if (projectResponse.data.code === 200) {
      const projectData = projectResponse.data.data;
      form.project_name = projectData.projectName || '';
      form.project_code = projectData.projectCode || '';
      form.client_name = projectData.clientName || '';
      form.client_contact = projectData.clientContact || '';
      form.client_phone = projectData.clientPhone || '';
      form.project_goal = projectData.projectGoal || '';
    }

    // 获取需求详情
    const requirementResponse = await axios.get(`/api/requirements/project/${projectId}`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    if (requirementResponse.data.code === 200 && requirementResponse.data.data && requirementResponse.data.data.length > 0) {
      const requirementData = requirementResponse.data.data[0];

      // 文件基本信息
      form.file_name = requirementData.fileName || '';
      form.version = requirementData.version || '';
      form.priority = getPriorityText(requirementData.priority) || '中';

      // 产品设计细节
      form.product_shape = getProductShapeText(requirementData.productShape) || '';
      form.product_structure = getProductStructureText(requirementData.productStructure) || '';
      form.closure_type = getClosureTypeText(requirementData.closureType) || '';
      form.decoration = requirementData.decoration || '';
      form.pocket_type = getPocketTypeText(requirementData.pocketType) || '';
      form.dimensions = requirementData.dimensions || '';
      form.color_code = requirementData.colorCode || '';
      form.color_shade = getColorShadeText(requirementData.colorShade) || '';
      form.pattern_type = getPatternTypeText(requirementData.patternType) || '';
      form.pattern_location = requirementData.patternLocation || '';
      form.pattern_size = requirementData.patternSize || '';

      // 材质偏好
      form.leather_type = getLeatherTypeText(requirementData.leatherType) || '';
      form.leather_thickness = requirementData.leatherThickness || '';
      form.leather_finish = getLeatherFinishText(requirementData.leatherFinish) || '';
      form.lining_type = getLiningTypeText(requirementData.liningType) || '';
      form.lining_color = requirementData.liningColor || '';

      // 预期效果
      form.softness = getSoftnessText(requirementData.softness) || '';
      form.durability = getDurabilityText(requirementData.durability) || '';
      form.water_resistance = getWaterResistanceText(requirementData.waterResistance) || '';
      form.shine = getShineText(requirementData.shine) || '';

      // 工艺要求
      form.cutting_accuracy = getCuttingAccuracyText(requirementData.cuttingAccuracy) || '';
      form.sewing_density = getSewingDensityText(requirementData.sewingDensity) || '';
      form.assembly_order = requirementData.assemblyOrder || '';

      // 成本要求
      form.material_cost = requirementData.materialCost || '';
      form.processing_cost = requirementData.processingCost || '';

      // 生产可行性
      form.process_feasibility = requirementData.processFeasibility || '';
      form.production_time = requirementData.productionTime || '';

      // 其他信息
      form.requirement_desc = requirementData.requirementDesc || '';
      form.notes = requirementData.notes || '';
    }
  } catch (error) {
    ElNotification.error({
      title: '错误',
      message: '获取项目详情失败',
    });
    console.error('获取项目详情失败:', error);
  } finally {
    isLoading.value = false;
  }
};

// 提交表单
const onSubmit = async () => {
  try {
    isSubmitting.value = true;

    // 验证项目基本信息
    if (!form.project_name) {
      ElNotification.warning({ title: '警告', message: '请填写项目名称' });
      return;
    }

    const token = localStorage.getItem('token');
    let projectId = route.params.id;
    let isNewProject = !projectId || projectId === 'new';

    // 创建或更新项目
    const projectData = {
      projectName: form.project_name,
      projectCode: form.project_code,
      clientName: form.client_name,
      clientContact: form.client_contact,
      clientPhone: form.client_phone,
      projectGoal: form.project_goal,
      status: 1,
    };

    let projectResponse;
    if (isNewProject) {
      projectResponse = await axios.post('/api/projects', projectData, {
        headers: { Authorization: `Bearer ${token}` }
      });
      projectId = projectResponse.data.data.id;
    } else {
      projectResponse = await axios.put(`/api/projects/${projectId}`, projectData, {
        headers: { Authorization: `Bearer ${token}` }
      });
    }

    // 第二步：创建或更新需求详情
    // 准备需求详情数据
    const requirementsToSave = form.requirements.map(requirement => ({
      projectId: projectId,
      fileName: requirement.file_name || `未命名需求_${new Date().getTime()}`,
      version: requirement.version || 'V1.0',
      requirementDesc: requirement.requirement_desc || '',
      priority: mapPriority(requirement.priority),
      productShape: mapProductShape(requirement.product_shape),
      productStructure: mapProductStructure(requirement.product_structure),
      closureType: mapClosureType(requirement.closure_type),
      decoration: requirement.decoration,
      pocketType: mapPocketType(requirement.pocket_type),
      dimensions: requirement.dimensions,
      colorCode: requirement.color_code,
      colorShade: mapColorShade(requirement.color_shade),
      patternType: mapPatternType(requirement.pattern_type),
      patternLocation: requirement.pattern_location,
      patternSize: requirement.pattern_size,
      leatherType: mapLeatherType(requirement.leather_type),
      leatherThickness: requirement.leather_thickness,
      leatherFinish: mapLeatherFinish(requirement.leather_finish),
      liningType: mapLiningType(requirement.lining_type),
      liningColor: requirement.lining_color,
      softness: mapSoftness(requirement.softness),
      durability: mapDurability(requirement.durability),
      waterResistance: mapWaterResistance(requirement.water_resistance),
      shine: mapShine(requirement.shine),
      cuttingAccuracy: mapCuttingAccuracy(requirement.cutting_accuracy),
      sewingDensity: mapSewingDensity(requirement.sewing_density),
      assemblyOrder: requirement.assembly_order,
      materialCost: requirement.material_cost,
      processingCost: requirement.processing_cost,
      processFeasibility: requirement.process_feasibility,
      productionTime: requirement.production_time,
      notes: requirement.notes,
      requirementStatus: 'PENDING' // 默认状态
    }));

    // 4. 批量保存需求
    const savePromises = requirementsToSave.map(req =>
        axios.post('/api/requirements', req, {
          headers: { Authorization: `Bearer ${token}` }
        })
    );

    await Promise.all(savePromises);

    ElNotification.success({
      title: '成功',
      message: isNewProject ? '项目创建成功' : '项目更新成功',
    });
    router.push('/projects');
  } catch (error) {
    ElNotification.error({
      title: '错误',
      message: `提交失败: ${error.response?.data?.message || error.message}`
    });
  } finally {
    isSubmitting.value = false;
  }
};

// 返回项目列表
const goBack = () => {
  router.push('/projects');
};

// 映射函数，将中文值映射为后端需要的枚举值
const mapPriority = (value) => {
  const map = {
    '高': 'HIGH',
    '中': 'MEDIUM',
    '低': 'LOW'
  };
  return map[value] || 'MEDIUM';
};

const mapProductShape = (value) => {
  if (!value) return null;
  const map = {
    '方形': 'SQUARE',
    '长方形': 'RECTANGLE',
    '流线型': 'STREAMLINE',
    '圆形': 'CIRCLE',
    '不规则': 'IRREGULAR'
  };
  return map[value] || null;
};

const mapProductStructure = (value) => {
  if (!value) return null;
  const map = {
    '单层': 'SINGLE_LAYER',
    '多层': 'MULTI_LAYER',
    '带口袋': 'WITH_POCKETS',
    '可折叠': 'FOLDABLE'
  };
  return map[value] || null;
};

const mapClosureType = (value) => {
  if (!value) return null;
  const map = {
    '拉链': 'ZIPPER',
    '纽扣': 'BUTTON',
    '磁吸': 'MAGNETIC',
    '挂钩': 'HOOK'
  };
  return map[value] || null;
};

const mapPocketType = (value) => {
  if (!value) return null;
  const map = {
    '拉链袋': 'ZIPPERED',
    '贴袋': 'PATCH',
    '隐形袋': 'HIDDEN'
  };
  return map[value] || null;
};

const mapColorShade = (value) => {
  if (!value) return null;
  const map = {
    '深色': 'DARK',
    '浅色': 'LIGHT',
    '中性色': 'NEUTRAL'
  };
  return map[value] || null;
};

const mapPatternType = (value) => {
  if (!value) return null;
  const map = {
    '压花': 'EMBOSSED',
    '印花': 'PRINTED',
    '雕刻': 'ENGRAVED'
  };
  return map[value] || null;
};

const mapLeatherType = (value) => {
  if (!value) return null;
  const map = {
    '全粒面': 'FULL_GRAIN',
    '反绒': 'SUEDE',
    '人造革': 'ARTIFICIAL'
  };
  return map[value] || null;
};

const mapLeatherFinish = (value) => {
  if (!value) return null;
  const map = {
    '哑光': 'MATTE',
    '亮光': 'BRIGHT'
  };
  return map[value] || null;
};

const mapLiningType = (value) => {
  if (!value) return null;
  const map = {
    '涤纶': 'POLYESTER',
    '超纤': 'MICROFIBER'
  };
  return map[value] || null;
};

const mapSoftness = (value) => {
  if (!value) return null;
  const map = {
    '非常柔软': 'VERY_SOFT',
    '适中': 'MODERATELY_SOFT',
    '偏硬': 'STIFF'
  };
  return map[value] || null;
};

const mapDurability = (value) => {
  if (!value) return null;
  const map = {
    '高': 'HIGH',
    '中': 'MEDIUM',
    '低': 'LOW'
  };
  return map[value] || null;
};

const mapWaterResistance = (value) => {
  if (!value) return null;
  const map = {
    '完全防水': 'WATERPROOF',
    '防泼水': 'SPLASH_PROOF',
    '不防水': 'NOT_WATERPROOF'
  };
  return map[value] || null;
};

const mapShine = (value) => {
  if (!value) return null;
  const map = {
    '哑光': 'MATTE',
    '半哑': 'SEMI_MATTE',
    '自然': 'NATURAL',
    '高光': 'HIGH_GLOSS'
  };
  return map[value] || null;
};

const mapCuttingAccuracy = (value) => {
  if (!value) return null;
  const map = {
    '±1mm': '1MM',
    '±2mm': '2MM',
    '±3mm': '3MM'
  };
  return map[value] || null;
};

const mapSewingDensity = (value) => {
  if (!value) return null;
  const map = {
    '8-9针/英寸': '8_9',
    '10-12针/英寸': '10_12',
    '12-14针/英寸': '12_14'
  };
  return map[value] || null;
};

// 反向映射函数，将后端枚举值映射为中文文本
const getPriorityText = (value) => {
  if (!value) return null;
  const map = {
    'HIGH': '高',
    'MEDIUM': '中',
    'LOW': '低'
  };
  return map[value] || '中';
};

const getProductShapeText = (shape) => {
  if (!value) return null;
  const shapes = {
    'SQUARE': '方形',
    'RECTANGLE': '长方形',
    'STREAMLINE': '流线型',
    'CIRCLE': '圆形',
    'IRREGULAR': '不规则'
  };
  return shapes[shape] || '';
};

const getProductStructureText = (structure) => {
  if (!value) return null;
  const structures = {
    'SINGLE_LAYER': '单层',
    'MULTI_LAYER': '多层',
    'WITH_POCKETS': '带口袋',
    'FOLDABLE': '可折叠'
  };
  return structures[structure] || '';
};

const getClosureTypeText = (type) => {
  if (!value) return null;
  const types = {
    'ZIPPER': '拉链',
    'BUTTON': '纽扣',
    'MAGNETIC': '磁吸',
    'HOOK': '挂钩'
  };
  return types[type] || '';
};

const getPocketTypeText = (type) => {
  if (!value) return null;
  const types = {
    'ZIPPERED': '拉链袋',
    'PATCH': '贴袋',
    'HIDDEN': '隐形袋'
  };
  return types[type] || '';
};

const getColorShadeText = (shade) => {
  if (!value) return null;
  const shades = {
    'DARK': '深色',
    'LIGHT': '浅色',
    'NEUTRAL': '中性色'
  };
  return shades[shade] || '';
};

const getPatternTypeText = (type) => {
  if (!value) return null;
  const types = {
    'EMBOSSED': '压花',
    'PRINTED': '印花',
    'ENGRAVED': '雕刻'
  };
  return types[type] || '';
};

const getLeatherTypeText = (type) => {
  if (!value) return null;
  const types = {
    'FULL_GRAIN': '全粒面',
    'SUEDE': '反绒',
    'ARTIFICIAL': '人造革'
  };
  return types[type] || '';
};

const getLeatherFinishText = (finish) => {
  if (!value) return null;
  const finishes = {
    'MATTE': '哑光',
    'BRIGHT': '亮光'
  };
  return finishes[finish] || '';
};

const getLiningTypeText = (type) => {
  if (!value) return null;
  const types = {
    'POLYESTER': '涤纶',
    'MICROFIBER': '超纤'
  };
  return types[type] || '';
};

const getSoftnessText = (softness) => {
  if (!value) return null;
  const softnessTypes = {
    'VERY_SOFT': '非常柔软',
    'MODERATELY_SOFT': '适中',
    'STIFF': '偏硬'
  };
  return softnessTypes[softness] || '';
};

const getDurabilityText = (durability) => {
  if (!value) return null;
  const durabilityTypes = {
    'HIGH': '高',
    'MEDIUM': '中',
    'LOW': '低'
  };
  return durabilityTypes[durability] || '';
};

const getWaterResistanceText = (resistance) => {
  if (!value) return null;
  const resistanceTypes = {
    'WATERPROOF': '完全防水',
    'SPLASH_PROOF': '防泼水',
    'NOT_WATERPROOF': '不防水'
  };
  return resistanceTypes[resistance] || '';
};

const getShineText = (shine) => {
  if (!value) return null;
  const shineTypes = {
    'MATTE': '哑光',
    'SEMI_MATTE': '半哑',
    'NATURAL': '自然',
    'HIGH_GLOSS': '高光'
  };
  return shineTypes[shine] || '';
};

const getCuttingAccuracyText = (accuracy) => {
  if (!value) return null;
  const accuracyTypes = {
    '1MM': '±1mm',
    '2MM': '±2mm',
    '3MM': '±3mm'
  };
  return accuracyTypes[accuracy] || '';
};

const getSewingDensityText = (density) => {
  if (!value) return null;
  const densityTypes = {
    '8_9': '8-9针/英寸',
    '10_12': '10-12针/英寸',
    '12_14': '12-14针/英寸'
  };
  return densityTypes[density] || '';
};

// 验证颜色代码是否有效
const isValidColor = (color) => {
  if (!color) return false;
  
  // 检查是否是有效的十六进制颜色值
  if (/^#([0-9A-F]{3}){1,2}$/i.test(color)) {
    return true;
  }
  
  // 检查是否是有效的rgb或rgba颜色值
  if (/^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/i.test(color) ||
      /^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*[0-9\.]+\s*\)$/i.test(color)) {
    return true;
  }
  
  // 创建一个临时元素来测试颜色名称是否有效
  const tempElement = document.createElement('div');
  tempElement.style.color = color;
  
  // 如果颜色设置成功，则返回true
  return tempElement.style.color !== '';
};

// 页面加载时执行
onMounted(() => {
  fetchProjectOptions();
  fetchProjectDetails();
});
</script>

<style scoped>
.requirements-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
}

.requirement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.requirement-header span {
  font-weight: bold;
  font-size: 16px;
}

/* 内外层Tabs视觉区分 */
:deep(.outer-tabs) {
  .el-tabs__item {
    padding: 0 20px;
    height: 40px;
  }
}

:deep(.inner-tabs) {
  .el-tabs__item {
    padding: 0 15px;
    height: 36px;
  }
}

/* 表单内容区域 */
.tab-content {
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  margin-top: 10px;
}

:deep(.el-tabs__item) {
  padding: 0 20px !important;
}

:deep(.el-tabs--card>.el-tabs__header .el-tabs__item) {
  border-left: 1px solid #e4e7ed;
}

:deep(.el-tabs--card>.el-tabs__header .el-tabs__item:first-child) {
  border-left: none;
}

.top-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
  transition: all 0.3s ease;
}

.top-left {
  display: flex;
  align-items: center;
  min-width: 300px;
}

.logo {
  height: 36px;
  margin-right: 12px;
  transition: transform 0.3s ease;
}

.logo:hover {
  transform: scale(1.05);
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  background: linear-gradient(45deg, #6a11cb, #2575fc);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.detail-title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  color: black;
  font-weight: bolder;
  padding: 0 20px;
}

.buttons {
  display: flex;
  gap: 10px;
  min-width: 120px;
}

.primary-button {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background: linear-gradient(45deg, #6a11cb, #2575fc);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.primary-button:hover {
  background: linear-gradient(45deg, #5a01bb, #1565ec);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.primary-button i {
  margin-right: 6px;
  font-size: 14px;
}

.main-content {
  padding: 20px;
  flex-grow: 1;
}

.form-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.form-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(to right, #f8f9fa, #ffffff);
  border-bottom: 1px solid #eaeaea;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
  position: relative;
  padding-left: 12px;
}

.card-header h2:before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background: linear-gradient(to bottom, #6a11cb, #2575fc);
  border-radius: 2px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.form-row .el-form-item {
  flex: 1;
  min-width: 250px;
}

.form-row .full-width {
  flex: 2;
  min-width: 100%;
}

.form-content {
  padding: 15px 0;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 10px;
}

.requirement-form :deep(.el-form-item__label) {
  font-weight: bold;
  color: #606266;
}

.requirement-form :deep(.el-input__inner) {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.requirement-form :deep(.el-input:hover .el-input__inner) {
  border-color: #6a11cb;
}

.requirement-form :deep(.el-input__inner:focus) {
  border-color: #6a11cb;
  box-shadow: 0 0 0 2px rgba(106, 17, 203, 0.2);
}

.requirement-form :deep(.el-textarea__inner) {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.requirement-form :deep(.el-textarea:hover .el-textarea__inner) {
  border-color: #6a11cb;
}

.requirement-form :deep(.el-textarea__inner:focus) {
  border-color: #6a11cb;
  box-shadow: 0 0 0 2px rgba(106, 17, 203, 0.2);
}

.requirement-form :deep(.el-select) {
  width: 100%;
}

.requirement-form :deep(.el-select:hover .el-input__inner) {
  border-color: #6a11cb;
}

.requirement-form :deep(.el-select .el-input.is-focus .el-input__inner) {
  border-color: #6a11cb;
  box-shadow: 0 0 0 2px rgba(106, 17, 203, 0.2);
}

/* 颜色代码预览样式 */
.color-preview-wrapper {
  position: relative;
}

.color-preview {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 24px;
  height: 24px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.requirement-form :deep(.el-tabs__nav) {
  border-radius: 4px;
  overflow: hidden;
}

.requirement-form :deep(.el-tabs__item) {
  transition: all 0.3s ease;
  height: 40px;
  line-height: 40px;
}

.requirement-form :deep(.el-tabs__item.is-active) {
  background-color: #f0f2f5;
  font-weight: bold;
  color: #6a11cb;
}

.requirement-form :deep(.el-tabs__active-bar) {
  background: linear-gradient(45deg, #6a11cb, #2575fc);
  height: 3px;
}
</style>